package com.jimple.apps.RssClient.ui;

import java.io.File;
import java.util.Iterator;
import java.util.Properties;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import com.jimple.apps.RssClient.Properties.LoadFeeds;
import com.jimple.apps.RssClient.Properties.SaveFeeds;

public class FeedPropUI {
	private boolean niceClose = false;
	Text name;
	Text url;
	Table table;
	Shell shell;
	Display display;
	UiSetup uis;

	public FeedPropUI(Display display, UiSetup uis) {
		try {
			this.uis = uis;
			// SHELL CREATION
			this.display = display;
			shell = new Shell(display);
			shell.setText("Feed Config");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void launchGui() {
		try {

			setupPaths();

			// GridData shellData = new GridData();
			shell.setSize(300, 400);
			shell.setLayout(new GridLayout());
			shell.addShellListener(new ShellListener() {
				public void shellActivated(ShellEvent arg0) {
				}

				public void shellClosed(ShellEvent arg0) {
					if (!niceClose) {
						uis.setFeedRefreshNeeded(false);
					}

				}

				public void shellDeactivated(ShellEvent arg0) {
				}

				public void shellDeiconified(ShellEvent arg0) {
				}

				public void shellIconified(ShellEvent arg0) {
				}

			});

			Composite parent = new Composite(shell, SWT.NONE);

			GridLayout groupGL = new GridLayout();
			groupGL.numColumns = 2;
			groupGL.makeColumnsEqualWidth = true;
			groupGL.horizontalSpacing = 10;
			parent.setLayout(groupGL);
			parent.setLayoutData(new GridData(GridData.FILL_BOTH));

			Label lab = new Label(parent, SWT.NONE);
			lab.setText("Current Feeds");
			GridData labelData = new GridData();
			labelData.horizontalSpan = 2;
			table = new Table(parent, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL
					| SWT.LINE_SOLID | SWT.SINGLE | SWT.FULL_SELECTION);
			table.setHeaderVisible(true);
			GridData tabledata = new GridData(GridData.FILL_BOTH);
			tabledata.horizontalSpan = 2;
			tabledata.grabExcessHorizontalSpace = true;
			tabledata.heightHint = 100;
			table.setLayoutData(tabledata);

			String[] titles = { "Feed Name", "Feed URL" };
			int[] widths = { 100, 200 };

			TableColumn column = null;
			for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
				column = new TableColumn(table, SWT.LEFT);
				column.setText(titles[loopIndex]);
				column.setWidth(widths[loopIndex]);
			}

			// start of group content
			GridData groupData = new GridData(GridData.FILL_BOTH);
			groupData.grabExcessHorizontalSpace = true;
			groupData.horizontalSpan = 2;
			Group inputGroup = new Group(parent, SWT.NONE);
			inputGroup.setText("Feed Controls");
			inputGroup.setLayout(groupGL);
			inputGroup.setLayoutData(groupData);

			Label namelabel = new Label(inputGroup, SWT.NONE);
			namelabel.setText("Feed Name:");
			name = new Text(inputGroup, SWT.BORDER);
			name.setText("");
			GridData nameData = new GridData(GridData.FILL_BOTH);
			nameData.horizontalSpan = 2;
			nameData.grabExcessHorizontalSpace = true;
			name.setLayoutData(nameData);

			lab = new Label(inputGroup, SWT.NONE);
			lab.setText("Feed URL:");
			url = new Text(inputGroup, SWT.BORDER);
			url.setText("http://");
			url.setLayoutData(nameData);
			url.addTraverseListener(new TraverseListener() {

				public void keyTraversed(TraverseEvent e) {
					if (e.detail == SWT.TRAVERSE_TAB_NEXT) {
						addToTable();
						name.setFocus();
						e.doit = false;
					} else if (e.keyCode == 13) {
						saveAndClose();
					} else if (e.keyCode == 27) {
						shell.dispose();
					}

				}

			});

			GridData adddata = new GridData(GridData.FILL_HORIZONTAL);
			adddata.grabExcessHorizontalSpace = true;
			adddata.horizontalAlignment = SWT.CENTER;
			Button addButton = new Button(inputGroup, SWT.PUSH);
			addButton.setLayoutData(adddata);
			addButton.setText("Add");
			addButton.pack();

			addButton.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					if ((name.getText().equalsIgnoreCase(""))) {
						name.setFocus();
						name.selectAll();
					} else {
						addToTable();
					}
				}
			});

			GridData deletedata = new GridData(GridData.FILL_HORIZONTAL);
			deletedata.grabExcessHorizontalSpace = true;
			deletedata.horizontalAlignment = SWT.CENTER;
			Button deleteButton = new Button(inputGroup, SWT.PUSH);
			deleteButton.setLayoutData(deletedata);
			deleteButton.setText("Remove");
			deleteButton.pack();

			deleteButton.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					if (table.getSelectionIndex() == -1) {

						return;
					}
					table.remove(table.getSelectionIndex());
					table.setSelection(table.getItems().length - 1);
				}
			});

			Button insertButton = new Button(parent, SWT.PUSH);
			insertButton.setText("Save Feeds");
			GridData insertData = new GridData(GridData.FILL_BOTH);
			insertData.grabExcessHorizontalSpace = true;
			insertData.grabExcessVerticalSpace = false;
			insertData.horizontalAlignment = SWT.CENTER;
			insertData.horizontalSpan = 2;
			insertButton.setLayoutData(insertData);
			insertButton.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					saveAndClose();
				}
			});

			initFeeds();

			shell.pack();
			Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
			Rectangle screen = display.getMonitors()[0].getBounds();
			shell.setBounds((screen.width - size.x) / 2,
					(screen.height - size.y) / 2, size.x, size.y);
			shell.open();
			name.setFocus();
			name.selectAll();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
			}
			// display.dispose();
		} catch (Exception aa) {
			aa.printStackTrace();
		}
	}

	private void setupPaths() {
		String appdata = System.getenv("APPDATA");
		File RSSDir = new File(appdata, "RSSLight");
		if (!RSSDir.exists()) {
			RSSDir.mkdirs();
		}

		// Iterator iter = System.getenv().keySet().iterator();
		// while (iter.hasNext()) {
		// String key = (String) iter.next();
		// System.out.println(key + " = " + System.getenv().get(key));
		// }

	}

	private void initFeeds() {
		Properties feeds = LoadFeeds.LoadFeeds();
		Iterator iter = feeds.keySet().iterator();
		while (iter.hasNext()) {
			String name = (String) iter.next();
			String url = (String) feeds.getProperty(name);
			addItemToTable(name, url);
		}

	}

	private void addItemToTable(String name, String url) {
		TableItem item = new TableItem(table, SWT.NULL);
		item.setText(0, name);
		item.setText(1, url);
	}

	private void addToTable() {
		String feedName = name.getText().trim();
		String feedUrl = url.getText().trim();
		if (feedName.equalsIgnoreCase("")) {
			return;
		}
		if (feedUrl.equalsIgnoreCase("")) {
			return;
		}

		TableItem item = new TableItem(table, SWT.NULL);
		item.setText(0, feedName);
		item.setText(1, feedUrl);

		name.setText("");
		name.forceFocus();
		name.setFocus();
	}

	private void saveAndClose() {
		niceClose = true;
		uis.setFeedRefreshNeeded(true);
		TableItem[] items = table.getItems();
		Properties props = new Properties();
		for (int i = 0; i < items.length; i++) {
			String feedName = items[i].getText(0);
			String feedUrl = items[i].getText(1);
			props.put(feedName, feedUrl);
		}
		SaveFeeds.SaveProperties(props);
		shell.close();
		shell.dispose();
	}
}
